package cn.wolfcode.wolf2w.util;

import cn.wolfcode.wolf2w.query.QueryObject;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public class PageUtils {

	public static <T> Page<T> page (MongoTemplate template,Query query, Class<T> clz, QueryObject qo,Sort sort){
		long total = template.count(query,clz);
		// 如果查询出来的数据为0条,返回一个空对象
		if(total == 0){
			return Page.empty();
		}
		// 合理化分页
		Long totalPage = total % qo.getPageSize() == 0 ? total / qo.getPageSize() : total / qo.getPageSize()+1;
		if(qo.getCurrentPage() > totalPage){
			qo.setCurrentPage(totalPage.intValue());
		}

		// 拼接分页、排序规则
		Pageable pageable;
		if(sort != null){
			pageable = PageRequest.of(qo.getCurrentPage() - 1,qo.getPageSize(),sort);
		}else {
			pageable = PageRequest.of(qo.getCurrentPage() - 1,qo.getPageSize());
		}
		query.with(pageable);

		// 查询分页数据
		List<T> list = template.find(query,clz);
		return new PageImpl<T>(list,pageable,total);
	}
}
